<template>
	<view>
		<view class="CommissionRank">
			<view class="header">
				<view class="rank">
					<view v-if="position>0">您目前的排名第<text class="num">{{position}}</text>名</view>
					<view v-else>您目前暂无排名</view>
					<view v-if="isStaff" class="mg-t-lg text-bold lay-c-c" style="text-decoration: underline;" @click="onTapExportExcel">导出EXCEL...</view>
				</view>
			</view>
			<view class="wrapper">
				<!--
				<view class="nav acea-row row-around">
					<view style="color:red" @click="onTapRankType">
						<text>{{rankTypeNames[currRankType]}}</text>
						<text class="iconfont icon-xiala1" style="margin-left: 10rpx; display: inline-block; position: relative; transform: rotate(180deg); -webkit-transform: rotate(180deg);"></text>
					</view>
				</view>-->
				<MyTab2 class="tab pd-xl" :items="ponds" :onChange="onRankTypeChange"></MyTab2>
				
				<scroll-view scroll-y scroll-with-animation class="list">
					<view class="item acea-row row-between-wrapper" v-for="(item,index) in rankList" :key="index">
						<view class="num" v-if="index <= 2">
							<image :src="'/static/images/medal0'+(index+1)+'.png'"></image>
						</view>
						<view class="num" v-else>
							{{index+1}}
						</view>
						<view class="picTxt acea-row row-between-wrapper">
							<view class="pictrue">
								<image :src="item.userAvatar ? item.userAvatar : '/static/images/f.png'"></image>
							</view>
							<view class="text line1">{{item.userNickname}}</view>
						</view>
						<view>{{item.seatNo}}号</view>
						<view class="people font-color">{{item.ypRetPriceType==2?item.totalRetNum+'条':item.totalRetWeight+'斤'}}</view>
					</view>
					
					<view class="vspace-xxl"></view>
				</scroll-view>
			</view>
			
			<view v-if="sumWeight && sumWeight.length > 0" class="fix-view">
				<view class="lay-c-c title pd-md">{{sumWeight}}</view>
			</view>
		</view>
		
		<!-- <view style="margin: 40rpx; text-align: center;color: gray;"> ... 只排前{{limitRank}}名，未进榜的钓友们加油啊😕 </view> -->
		
		<!-- ====== begin 日期选择对话框 ====== -->
		<view :class="{modal:true, 'bottom-modal':true, show:showDatePickerDialog}" @click="showDatePickerDialog=false">
			<view class="dialog" @click.stop="">
				<view class="lay-c-c mg-md title">
					选择导出日期
				</view>
				
				<picker-view :indicator-style="indicatorStyle" :value="datePickerValue" @change="onDatePickerChange" class="picker-view">
					<picker-view-column>
						<view class="lay-c-c" v-for="(item,index) in datePickerYears" :key="index"><text>{{item}}年</text></view>
					</picker-view-column>
					<picker-view-column>
						<view class="lay-c-c" v-for="(item,index) in datePickerMonths" :key="index"><text>{{item}}月</text></view>
					</picker-view-column>
					<picker-view-column>
						<view class="lay-c-c" v-for="(item,index) in datePickerDays" :key="index"><text>{{item}}日</text></view>
					</picker-view-column>
				</picker-view>
				
				<view class="lay-c-c mg-v-md mg-h-xxxl">
					<button class="btn bk-white flex1 title" @click="onTapDatePickerOK">导出</button>
				</view>
				
			</view>
		</view>
		<!-- ====== end 日期选择对话框 ====== -->
		
		<!-- ====== begin 授权功能 ====== -->
		<!-- #ifdef MP -->
		<authorize @onLoadFun="onLoadFun" :isAuto="isAuto" :isShowAuth="isShowAuth" @authColse="authColse"></authorize>
		<!-- #endif -->
		<!-- #ifndef H5 -->
		<passwordPopup></passwordPopup>
		<!-- #endif -->
		<!-- ====== end 授权功能 ====== -->
	</view>
</template>
<script>
	// +----------------------------------------------------------------------
	// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
	// +----------------------------------------------------------------------
	// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
	// +----------------------------------------------------------------------
	// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
	// +----------------------------------------------------------------------
	// | Author: CRMEB Team <admin@crmeb.com>
	// +----------------------------------------------------------------------
	import {
		queryFshRanks,
		queryFshRanks2
	} from '@/api/fsh.js';
	import {
		toLogin
	} from '@/libs/login.js';
	
	import {
		HTTP_REQUEST_URL,
		HEADER,
		TOKENNAME
	} from '@/config/app';
	
	import store from '@/store';
	
	// ====== begin 授权功能 ======
	import {
		mapGetters
	} from "vuex";
	// #ifdef MP
	import authorize from '@/components/Authorize';
	// #endif
	// #ifndef H5
	import passwordPopup from '@/components/passwordPopup';
	// #endif
	// ====== end 授权功能 ======
	
	import MyTab2 from '@/components/my/MyTab2.vue';
	
	export default {
		// ====== begin 授权功能 ======
		components: {
			// #ifndef H5
			passwordPopup,
			// #endif
			// #ifdef MP
			authorize ,
			// #endif
			MyTab2
		},
		// ====== end 授权功能 ======
		data() {
			
			// begin 日期选择对话框
			const date = new Date()
			
			const fromYear = 2023;
			const years = [];
			for (let i = fromYear; i <= date.getFullYear(); i++) {
				years.push(i)
			}
			const year = date.getFullYear() - fromYear;
			
			const months = []
			for (let i = 1; i <= 12; i++) {
				months.push(i)
			}
			const month = date.getMonth() + 1
			
			const days = []
			for (let i = 1; i <= 31; i++) {
				days.push(i)
			}
			const day = date.getDate()
			// end 日期选择对话框
						
			return {
				// ====== begin 授权功能 ======
				isAuto: false,
				isShowAuth: false,
				// ====== end 授权功能 ======
				
				ponds: [{
					name: '',
					subItems: {
						name: '',
					}
				}],
				// rankTypeNames: ["综合排名"],
				currRankType: 0,
				active: 0,
				rankList: [{
					totalRetWeight: 125.71,
					userAvatar: "https://thirdwx.qlogo.cn/mmopen/vi_32/Pb6FbEYnh2ZDfd7WicKf8yMicUK2dNGvPVKIvWJSjvFcib8lhgu79A54SshibBM90HS1ZRDRMbUTsBNo9tz7rgK5Gw/132",
					userId: 2,
					userNickname: "水上"
				}],
				page: 1,
				limit: 10,
				loadend: false,
				loading: false,
				loadTitle: '加载更多',
				type: 'week',
				position: 0,
				isAuto: false, //没有授权的不会自动授权
				isShowAuth: false ,//是否隐藏授权
				limitRank: 5, 
				sumWeight: '',
				isStaff: '', // 是否是工作人员
				
				// begin 日期选择对话框
				datePickerYears: years,
				datePickerMonths: months,
				datePickerDays: days,
				// datePickerYearValue: year,
				// datePickerMonthValue: month,
				// datePickerDayValue: day,
				datePickerValue: [years.length-1, month-1, day-1],
				showDatePickerDialog: false
				// end 日期选择对话框
			};
		},
		computed: mapGetters(['isLogin']), // ====== 授权功能 ======
		onLoad(options) {
			this.merId = options.merId;
			//this.ponds = JSON.parse(options.ponds); // uni-app之页面间传递和接收数组 https://www.cnblogs.com/luyj00436/p/15323488.html
			//this.rankTypeNames = this.rankTypeNames.concat(this.ponds.map(a=>a.storeName));
			//console.log("fsh_rank::onLoad, ponds=%o, rankTypeNames=%o", this.ponds, this.rankTypeNames);
			console.log("fsh_rank::onLoad, merId="+this.merId);
			
			if (this.isLogin) {
				queryFshRanks2(this.merId, 0, 0, '').then(res=>{
					console.log("queryFshRanks2, res:", res);
					this.ponds = res.entity.ponds.map(a=>{
						a.subCurr = 0;
						return a;
					});
					this.rankList = res.entity.ranks;
					this.sumWeight = res.entity.sumWeight || '';
					this.isStaff = true; //res.entity.isStaff;
				}).catch(err=>{
					console.error("queryFshRanks2, err:", err);
				})
			} else {
				// #ifdef H5 || APP-PLUS
				toLogin();
				// #endif 
				// #ifdef MP
				this.isAuto = true;
				this.$set(this, 'isShowAuth', true)
				// #endif
			}
		},
		methods: {
			// ====== begin 授权功能 ======
			// 打开授权
			openAuto() {
				this.isAuto = true;
				this.isShowAuth = true;
				console.log("openAuto, this.isShowAuth=true");
			},
			// 授权回调
			onLoadFun(userInfo) {
				console.log("onLoadFunc, userInfo:", userInfo);
				if(userInfo) { // 得到userInfo，说明登录成功，隐藏授权；否则继续显示授权
					this.isShowAuth = false;
					this.getFshRankList();
				}
			},
			// 授权关闭
			authColse(e) {
				this.isShowAuth = e
				console.log("authColse, this.isShowAuth="+this.isShowAuth);
			},
			// ====== end 授权功能 ======
			
			// onTapRankType() {
			// 	let that = this;
			// 	uni.showActionSheet({
			// 		itemList: that.rankTypeNames,
			// 		success: function (res) {
			// 			//console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
			// 			let productId;
			// 			if(res.tapIndex > 0)
			// 				productId = that.ponds[res.tapIndex-1].productId;
							
			// 			that.currRankType = res.tapIndex;
			// 			that.getFshRankList();
			// 		},
			// 		fail: function (res) {
			// 			//console.log(res.errMsg);
			// 		}
			// 	})
			// },
			getFshRankList(merId, pondId, partitionId, sku) {
				uni.showLoading({
					title: '加载中...'
				});
				queryFshRanks2(merId, pondId, partitionId, sku).then(res => {
					this.ponds = res.entity.ponds;
					this.rankList = res.entity.ranks;
					this.position = res.entity.userPos+1;
					this.sumWeight = res.entity.sumWeight || '';
					this.isStaff = true; //res.entity.isStaff;
					uni.hideLoading();
				}).catch(err => {
					this.sumWeight = '';
					uni.hideLoading();
				})
			},
			onRankTypeChange(curr, subcurr) {
				console.log(`onRankTypeChange, curr=${curr}, subcurr=${subcurr}`);
				queryFshRanks2(this.merId, this.ponds[curr].pondId, this.ponds[curr].partitionId, this.ponds[curr].subItems[subcurr].name).then(res=>{
					console.log("queryFshRanks2, res:", res);
					this.rankList = res.entity.ranks;
					this.sumWeight = res.entity.sumWeight || '';
					this.isStaff = true; //res.entity.isStaff;
				}).catch(err=>{
					this.sumWeight = '';
					console.error("queryFshRanks2, err:", err);
				})
			},
			onTapExportExcel() {
				this.showDatePickerDialog = true;
			}, 
			exportExcel(day) {
				uni.showLoading({title: '正在下载……'});
							
				var that = this;
				
				var header = JSON.parse(JSON.stringify(HEADER));
				delete header['content-type'];
				header[TOKENNAME] = 'Bearer ' + store.state.app.token;
				
				uni.downloadFile({
					url: HTTP_REQUEST_URL+"/api/gzyxsrv/mp/export/fshRanking?merId="+this.merId+'&day='+day,
					header: header,
					success: (data) => {
						uni.hideLoading();
						
						if (data.statusCode === 200) {
							//文件保存到本地
							uni.saveFile({
								tempFilePath: data.tempFilePath, //临时路径
								success: function(res) {
									uni.showToast({
										icon: 'success',
										mask: true,
										title: '导出成功' , 
										duration: 2000,
									});
												
									//自动打开文档查看
									setTimeout(() => {
										var filePath = res.savedFilePath;
										uni.openDocument({  //新开页面打开文档，支持格式：doc, xls, ppt, pdf, docx, xlsx, pptx。
											 filePath: filePath,
											showMenu: true,
											success: function (res) {
												 console.log('打开文档成功');
											}
										});
									}, 2000)
								},
							});
						}
					},
					fail: (err) => {
						uni.hideLoading();
						console.log(err);
						uni.showToast({
							icon: 'none',
							mask: true,
							title: '导出失败',
						});
					},
				});
			},
			
			// begin 日期选择对话框
			onDatePickerChange(e) {
				const val = e.detail.value
				this.datePickerValue = val;
			},
			
			onTapDatePickerOK() {
				this.showDatePickerDialog = false;
				const val = this.datePickerValue
				let day = this.datePickerYears[val[0]] + '-' + this.datePickerMonths[val[1]] + '-' + this.datePickerDays[val[2]];
				console.log("export day: " + day);
				this.exportExcel(day);
			}
			// end 日期选择对话框
		}
	}
</script>

<style scoped lang="scss">
	@import "@/leui.scss";
	
	$navHeight: 120rpx;
	.tab {
		height: $navHeight;
	}
	// .nav .item {
	// 	display: inline-block;
	// 	// height: 80rpx;
	// 	// line-height: 80rpx;
	// 	margin: 0 10rpx;
	// 	padding: 0 20rpx;
	// 	position: relative;
	// }
	
	// .nav .item.cur {
	// 	@extend .orange;
	// }
	
	$headerHeight: 330rpx;
	.CommissionRank .header {
		background: url("") no-repeat;
		width: 100%;
		height: $headerHeight;
		background-size: 100% 100%;
	}

	.CommissionRank .header .rank {
		font-size: 33rpx;
		color: #fff;
		position: absolute;
		top: 160rpx;
		left: 30rpx;
	}

	.CommissionRank .header .rank .num {
		font-size: 102rpx;
		font-weight: bold;
		margin: 0 10rpx;
	}

	.CommissionRank .wrapper {
		// width: 710rpx;
		background-color: #fff;
		// border-radius: 20rpx;
		// margin: 36rpx auto 0 auto;
	}

	// .CommissionRank .wrapper .nav {
	// 	height: 99rpx;
	// 	border-bottom: 2.5rpx solid #f3f3f3;
	// 	font-size: 30rpx;
	// 	font-weight: bold;
	// 	color: #999;
	// 	line-height: $navHeight;
	// }

	// .CommissionRank .wrapper .nav .item.font-color {
	// 	border-bottom: 4rpx solid #e93323;
	// }

	.list {
		height:calc(100vh - #{$headerHeight} - #{$navHeight} - 90rpx); // 对scss变量做calc计算不能直接使用$swiperHeight，要加#{}
		width:calc(100vw - 80rpx);
	}
	
	.CommissionRank .wrapper .list {
		padding: 0 30rpx;
	}

	.CommissionRank .wrapper .list .item {
		border-bottom: 1px solid #f3f3f3;
		height: 101rpx;
		font-size: 28rpx;
	}

	.CommissionRank .wrapper .list .item .num {
		color: #666;
		width: 70rpx;
	}

	.CommissionRank .wrapper .list .item .num image {
		width: 34rpx;
		height: 40rpx;
		display: block;
	}

	.CommissionRank .wrapper .list .item .picTxt {
		width: 350rpx;
	}

	.CommissionRank .wrapper .list .item .picTxt .pictrue {
		width: 68rpx;
		height: 68rpx;
	}

	.CommissionRank .wrapper .list .item .picTxt .pictrue image {
		width: 100%;
		height: 100%;
		display: block;
		border-radius: 50%;
	}

	.CommissionRank .wrapper .list .item .picTxt .text {
		width: 262rpx;
		color: #333;
	}

	.CommissionRank .wrapper .list .item .people {
		width: 175rpx;
		text-align: right;
	}
	
	.fix-view {
		position: fixed;
		top: px;
		bottom: 15rpx;
		left: 200rpx;
		border-radius: 100rpx;
		width: 300rpx;
		z-index: 1;
		color: #FFFFFF;
		background-color: rgba(255, 0, 0, 0.3);
	}
	
	// begin 日期选择对话框
	.picker-view {
		width: 750rpx;
		height: 600rpx;
		margin-top: 20rpx;
	}
	// end 日期选择对话框
		
</style>
